'use strict';
var io = require('socket.io');

exports.mainInit = function() {
	return new Main();
};

function Main() {
}

Main.prototype = {
	// 初始化
	init:function(http){
		//在线人员
		this.onlines = {};
		//在线人员数
		this.count = 0;
		//已打开办件
		this.fileList = {};
		this.fileList.length=0;
		
		var that = this;
		
		this.io = io(http);
		this.io.on('connection',function(socket){
			console.log('connection', socket.id);
			
			//注册用户
			//{userid:'',device:'',realname:''}
			socket.on('signin', function(data) {
				console.log('signin', socket.id + ":::" + JSON.stringify(data));
				
				//绑定uuid到socket
				socket.__uuid = data.userid;
				//已经存在的用户
				if(that.check(data.userid) == true) {
					that.addSock(data.userid, {
						id: socket.id,
						sock: socket,
						device: data.device,
						time: new Date().getTime()
					});
				} else {
					//新用户
					that.online(data.userid, {
						uuid: data.userid,
						name: data.realname,
						device: data.device,
						time: new Date().getTime(),
						socks: [{
							id: socket.id,
							sock: socket,
							device: data.device,
							time: new Date().getTime()
						}]
					});
				}
				//通知登录成功
				that.io.emit('online', {
					uuid: socket.__uuid,
					sockid: socket.id,
					data: data
				});
			});
			
			//断开链接
			socket.on('disconnect', function() {
				console.log('disconnect_' + socket.__uuid, socket.id);
				
				that.delSock(socket.__uuid, socket.id);
			});
			
			//心跳h+
			socket.on('heartbeat', function(data) {
				//socket.__live = true;
				//收到信号即时返回
				socket.emit('heartbeat', 'h+');
			});
			
			/*
			 * 办件相关
			 * */
			socket.on('fileOpen', function(obj) {
				if(!that.fileList[obj.fileId]){
					that.fileList[obj.fileId] = obj;
					//发布广播消息
					that.io.emit('fileOpenCallback', obj);
				}else{
					that.io.emit('fileOpenCallback?'+obj.userId, that.fileList[obj.fileId]);
				}
			});
			
			socket.on('closeFile', function(obj) {
				if(that.onlines[obj.userId] && that.fileList[obj.fileId]){//用户和文件都存在连接中
					if(obj.userId==that.fileList[obj.fileId].userId){//确认是同一个人
						var temp = that.fileList[obj.fileId];
						if(temp.userId == obj.userId){
							delete that.fileList[obj.fileId];
						}
						that.io.emit('closeFileCallback?'+obj.userId, {
							msg:'[OK]关闭办件['+obj.fileName+']成功',
							success:true,
							error:null
						});
					}else{
						that.io.emit('closeFileCallback?'+obj.userId, {
							msg:'[ERROR]该办件正由'+that.fileList[obj.fileId].userName+'办理中',
							success:true,
							error:null
						});
					}
				}else{
					that.io.emit('closeFileCallback?'+obj.userId, {
						msg:'[ERROR]无法关闭该办件',
						success:true,
						error:null
					});
				}
			});
		});
	},
	/**
	 * [check 检测用户是否存储]
	 * @param  {string} uuid 用户id
	 * @return {bool}
	 */
	check:function(uuid){
		console.log('check', uuid);
		
		if(!!this.onlines[uuid]) return true;
		return false;
	},
	/**
	 * [addSock 新增终端]
	 * @param {string} uuid   [用户id]
	 * @param {Object} socket [socket对象]
	 * @return {null}      [无返回值]
	 */
	addSock:function(uuid, socket) {
		this.onlines[uuid].socks.push(socket);
	},
	/**
	 * [online 添加在线用户]
	 * @param  {string} uuid [用户id]
	 * @param  {Object} data [在线人员对象]
	 * @return {null}      [无返回值]
	 */
	online:function(uuid, data) {
		console.log('online', data.socks.length);
		
		this.onlines[uuid] = data;
		this.count++;
	},
	/**
	 * [addSock 移除终端]
	 * @param {string} uuid   [用户id]
	 * @param {Object} socketid [socket对象id]
	 * @return {null}      [无返回值]
	 */
	delSock : function(uuid, socketid) {
		if(this.onlines[uuid] == undefined) return;
		var newSocks = [];
		var i = 0,
			l = this.onlines[uuid].socks.length;
		for(; i < l; i++) {
			if(this.onlines[uuid].socks[i].id != socketid)
				newSocks.push(this.onlines[uuid].socks[i]);
		}
		if(newSocks.length > 0) {
			this.onlines[uuid].socks = newSocks;
		} else {
			//所有终端都退出后，注销在线用户
			//this.offline(uuid);
			this.onlines[uuid].socks = [];
		}
	},
	/**
	 * [online 移除离线用户]
	 * @param  {string} uuid [用户id]
	 * @return {null}      [无返回值]
	 */
	offline : function(uuid) {
		console.log('offline');
		delete this.onlines[uuid];
		this.count--;
	}
};

/**
 * 对Date的扩展，将 Date 转化为指定格式的String 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 * 可以用 1-2 个占位符 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) eg: (new
 * Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 (new
 * Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 (new
 * Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 (new
 * Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 (new
 * Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
		"H+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	var week = {
		"0" : "\u65e5",
		"1" : "\u4e00",
		"2" : "\u4e8c",
		"3" : "\u4e09",
		"4" : "\u56db",
		"5" : "\u4e94",
		"6" : "\u516d"
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1,
				((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "")
						: "")
						+ week[this.getDay() + ""]);
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
};